package com.ruoyi.project.wx.service.impl;

import cc.openkit.common.KitUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bootdo.PageHelperUtils;
import com.ruoyi.common.utils.bootdo.R;
import com.ruoyi.common.utils.bootdo.UuidUtil;
import com.ruoyi.idworker.Id;
import com.ruoyi.project.mall.dao.MallCompanyUserDao;
import com.ruoyi.project.mall.dao.MallShopUserDao;
import com.ruoyi.project.mall.dao.OrderReviewDao;
import com.ruoyi.project.mall.domain.MallCompanyUserDO;
import com.ruoyi.project.mall.domain.MallShopUserDO;
import com.ruoyi.project.mall.domain.OrderReviewDO;
import com.ruoyi.project.shop.dao.ShopShopDao;
import com.ruoyi.project.shop.domain.ShopShopDO;
import com.ruoyi.project.wx.dao.*;
import com.ruoyi.project.wx.domain.*;
import com.ruoyi.project.wx.service.OrderOrderService;
import com.ruoyi.project.wx.service.Price;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;


@Service
public class OrderOrderServiceImpl implements OrderOrderService {
	@Autowired
	private OrderOrderDao orderOrderDao;
	@Autowired
	private OrderShippingDao orderShippingDao;
	@Autowired
	private MemberUserDao memberUserDao;
	@Autowired
	private MemberAddressDao memberAddressDao;
	@Autowired
	private GoodsProductDao goodsProductDao;
	@Autowired
	private OrderDetailDao orderDetailDao;
	@Autowired
	private CmsContentDao cmsContentDao;
	@Autowired
	private OrderComDao orderComDao;
	@Autowired
	private MemberCartDao memberCartDao;
	@Autowired
	private GoodsGoodsDao goodsGoodsDao;
	@Autowired
	private OrderComentDao orderComentDao;
	@Autowired
	private MemberCouponDao memberCouponDao;
	@Autowired
	private GoodsSpikeDao goodsSpikeDao;
	@Autowired
	private GoodsNineDao goodsNineDao;
	@Autowired
	private GoodsBargainDao goodsBargainDao;
	@Autowired
	private OrderBargainDao orderBargainDao;
	@Autowired
	private OrderBargainUserDao orderBargainUserDao;
	@Autowired
	private ShopExpressMessageDao shopExpressMessageDao;
	@Autowired
	private ShopExpressCodeDao shopExpressCodeDao;
	@Autowired
	private ShopExpressDetailsDao shopExpressDetailsDao;
	@Autowired
	private OrderExcelRecodeDao orderExcelRecodeDao;
	/*@Autowired
	private SysUserMapper useDao;*/
	@Autowired
	private OrderBackDao orderBackDao;
	@Autowired
	private MallShopUserDao mallShopUserDao;
	@Autowired
	private MallCompanyUserDao mallCompanyUserDao;
	@Autowired
	private OrderReviewDao orderReviewDao;
	@Autowired
	private ShopShopDao shopShopDao;
	@Autowired
	private OrderSetDao orderSetDao;

	
	@Override
	public OrderOrderDO get(String id){
		return orderOrderDao.get(id);
	}
	
	@Override
	public List<OrderOrderDO> list(Map<String, Object> map){
		return orderOrderDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return orderOrderDao.count(map);
	}
	
	@Override
	public int save(OrderOrderDO orderOrder){
		return orderOrderDao.save(orderOrder);
	}
	
	@Override
	public int update(OrderOrderDO orderOrder){
		return orderOrderDao.update(orderOrder);
	}
	
	@Override
	public int remove(String id){
		return orderOrderDao.remove(id);
	}
	
	@Override
	public int batchRemove(String[] ids){
		return orderOrderDao.batchRemove(ids);
	}

	public static AtomicInteger race= new AtomicInteger(0);

	/*购物车添加订单*/
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R addCartOrder(Map<String,Object> paramMap) {
		List<String> cartList = (List<String>)paramMap.get("cartList"); //商品集合
		String userId = paramMap.get("userId").toString();  //用户id
		String buyerMsg = paramMap.get("buyerMsg").toString();  //留言
		String couponId = paramMap.get("couponId").toString();  //优惠券id
		BigDecimal postFee = new BigDecimal(paramMap.get("postFee").toString());  //邮费
		String addressId = paramMap.get("addressId").toString();  //收货地址
		MemberUserDO user = memberUserDao.get(userId);
		Date date = new Date();

		//支付总金额
		BigDecimal goodsPrice = new BigDecimal(0);
		//订单交易号
		String payNum = KitUtil.getOrderCode();
		/*BigDecimal priceA = new BigDecimal(0);
		BigDecimal priceB = new BigDecimal(0);
		BigDecimal priceC = new BigDecimal(0);*/
		BigDecimal allPrice = new BigDecimal(0);
		for (String cartId : cartList) {
			MemberCartDO cart = memberCartDao.get(cartId);
			//订单表
			OrderOrderDO order = new OrderOrderDO();
			String order_sn = String.valueOf(Id.next());  //订单号
			order.setOrderSn(order_sn);
			order.setId(UuidUtil.get32UUID());
			order.setCreateAt(date);
			order.setPayNum(payNum);
			order.setUpdateAt(date);
			order.setUserId(userId);
			order.setBuyerMsg(buyerMsg);
			order.setBuyerNick(user.getName());
			order.setDelFlag(0);
			order.setExport(0);
			order.setSee(0);
			order.setPostFee(postFee);
			GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(cart.getGoodsId());
			order.setShopId(goodsGoodsDO.getShopId());

			//订单配送表
			MemberAddressDO memberAddress = memberAddressDao.get(addressId);
			OrderShippingDO shipping = new OrderShippingDO();
			shipping.setId(UuidUtil.get32UUID());
			shipping.setOrderId(order.getId());
			shipping.setReceiverName(memberAddress.getFullName());
			shipping.setReceiverPhone(memberAddress.getPhone());
			shipping.setReceiverProvince(memberAddress.getProvince());
			shipping.setReceiverCity(memberAddress.getCity());
			shipping.setReceiverCounty(memberAddress.getCounty());
			shipping.setReceiverTown(memberAddress.getTown());
			shipping.setReceiverAddress(memberAddress.getAddress());
			shipping.setCreateAt(date);
			shipping.setUpdateAt(date);
			shipping.setDelFlag(0);
			orderShippingDao.save(shipping);



			String goodId = cart.getGoodsId();   //商品id
			String productId = cart.getProductId(); //商品规格id
			int total = cart.getNum(); //商品数量
			GoodsProductDO product = goodsProductDao.get(productId);
			int stock = product.getStock();   //库存
			BigDecimal price = product.getPrice();
			//单价
			//price = goodsPrice(user, product, price);
			BigDecimal goodPrice = price.multiply(new BigDecimal(total));//总价
			goodsPrice = goodsPrice.add(goodPrice);
			//分销
			//rakeBack(user, order, total, product, price);
			

			OrderDetailDO detailDO = new OrderDetailDO();
			detailDO.setId(UuidUtil.get32UUID());
			detailDO.setGoodsId(goodId);
			detailDO.setOrderId(order.getId());
			detailDO.setProductId(productId);
			detailDO.setPrice(price);
			detailDO.setAllPrice(goodPrice);
			detailDO.setComent(0);
			detailDO.setCreateAt(date);
			detailDO.setDelFlag(0);
			detailDO.setTotal(total);
			orderDetailDao.save(detailDO);
			//修改商品库存、销量
			Map<String,Object> proMap = new HashMap<String,Object>();
			int newStock = stock-total;
			if (newStock < 0) {
				newStock = 0;
			}
			proMap.put("id",productId);
			proMap.put("newStock", newStock);
			proMap.put("oldStock", stock);
			int n = goodsProductDao.updateByOld(proMap);
			if (n == 0) {
				goodsProductDao.error(proMap);
			}
			//销量添加
			GoodsGoodsDO goods = goodsGoodsDao.get(goodId);
			int numSale = 0;
			if (goods.getNumSale() != null) {
				numSale = goods.getNumSale();
			}
			int num_sale = numSale+total;
			GoodsGoodsDO good = new GoodsGoodsDO();
			good.setId(goodId);
			good.setNumSale(num_sale);
			goodsGoodsDao.update(good);
			//删除购物车
			memberCartDao.remove(cartId);


			MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
			if (memberCouponDO != null) {
				BigDecimal couponMoney = memberCouponDO.getMoney();  //优惠金额
				allPrice = goodsPrice.add(postFee).subtract(couponMoney);  //订单总金额
				//修改用户优惠券
				MemberCouponDO couponDO = new MemberCouponDO();
				couponDO.setId(memberCouponDO.getId());
				couponDO.setStatus(1);
				couponDO.setOrderAt(date);
				couponDO.setUpdateAt(date);
				couponDO.setOrderId(order.getId());
				memberCouponDao.update(couponDO);
			} else {
				allPrice = goodsPrice.add(postFee);  //订单总金额
			}
			if(paramMap.get("type").toString().equals("5")){
				//审批订单表加入数据
				//1采购员
				saveOrderReview(userId, order);

			}

			//order_order补充
			order.setPayment(allPrice);
			order.setCouponId(couponId);
			order.setOrdertype(0);
			order.setStatus(1);
			order.setComent(0);
			orderOrderDao.save(order);
		}


		//开始分销
//		String intorId = user.getIntroUser();
		
		
		
		/*String intorId = user.getIntroUser();
		for (int i=1; i<3; i++) {
			if (intorId == null || "".equals(intorId)) {
				break;
			}
			MemberUserDO productUser = memberUserDao.get(intorId);
			if (productUser == null) {
				break;
			}
			int disbled = productUser.getDisabled();
			if (disbled == 1) {  //如果账号被冻结
				i--;
				intorId = productUser.getIntroUser();
				continue;
			}

			BigDecimal money = new BigDecimal(0);
			if (i == 1) {
				money = rebateOnePrice;
			} else if (i == 2) {
				money = rebateTwoPrice;
			}
			OrderComDO comDO = new OrderComDO();
			comDO.setId(UuidUtil.get32UUID());
			comDO.setCreateAt(date);
			comDO.setDelFlag(0);
			comDO.setOrderId(order.getId());
			comDO.setComPrice(money);
			comDO.setStatus(0);
			comDO.setUpdateAt(date);
			comDO.setUserId(intorId);
			orderComDao.save(comDO);
			intorId = productUser.getIntroUser();
		}*/
		Map<String,Object> map = new HashMap<>();
		map.put("allPrice",allPrice);
		map.put("payNum",payNum);



		return R.ok().put("data",map);
	}

	private void rakeBack(MemberUserDO user, OrderOrderDO order, int total, Price product, BigDecimal price) {
		//上级佣金
		BigDecimal upPriceA = product.getPrice();
		BigDecimal upPriceB = product.getPrice();
		BigDecimal upPriceC = product.getPrice();
		//返佣的id
		String introUserA ="";
		String introUserB ="";
		String introUserC ="";
		MemberUserDO upMemberUserDO = memberUserDao.get(user.getIntroUser());
		if(user.getLevel()=='A'){
//				price = product.getPriceA(); //单价
		}else if (user.getLevel()=='B'&&upMemberUserDO!=null&&upMemberUserDO.getDisabled()==0){
			upPriceA = product.getPriceA(); //A级单价
			upPriceA = price.subtract(upPriceA).multiply(new BigDecimal(total));
			introUserA=upMemberUserDO.getId();
		}else if (user.getLevel()=='C'&&upMemberUserDO!=null&&upMemberUserDO.getDisabled()==0){
			if(upMemberUserDO.getLevel()=='B'){
				BigDecimal PriceB = product.getPriceB(); //B级单价
				upPriceB = price.subtract(PriceB).multiply(new BigDecimal(total));
				introUserB=upMemberUserDO.getId();
				//查看B级有没有A级
				MemberUserDO memberUserDO = memberUserDao.get(upMemberUserDO.getIntroUser());
				if(memberUserDO!=null&&memberUserDO.getLevel()=='A'&&memberUserDO.getDisabled()==0){
					upPriceA = product.getPriceA(); //A级单价
					upPriceA= PriceB.subtract(upPriceA).multiply(new BigDecimal(total));
					introUserA=memberUserDO.getId();
				}
			}else if (upMemberUserDO.getLevel()=='A'){
				upPriceA = product.getPriceA(); //A级单价
				upPriceA= price.subtract(upPriceA).multiply(new BigDecimal(total));
				introUserA=upMemberUserDO.getId();
			}
		}else if(upMemberUserDO!=null&&upMemberUserDO.getDisabled()==0){
			if(upMemberUserDO.getLevel()=='B'){
				BigDecimal multiply = product.getPriceB(); //B级单价
				upPriceB = price.subtract(upPriceB).multiply(new BigDecimal(total));
				introUserB=upMemberUserDO.getId();
				//查看B级有没有A级
				MemberUserDO memberUserDO = memberUserDao.get(upMemberUserDO.getIntroUser());
				if(memberUserDO!=null&&memberUserDO.getLevel()=='A'&&memberUserDO.getDisabled()==0){
					upPriceA = product.getPriceA(); //A级单价
					upPriceA = multiply.subtract(upPriceA).multiply(new BigDecimal(total));
					introUserA=memberUserDO.getId();
				}
			}else if (upMemberUserDO.getLevel()=='A'){
				upPriceA = product.getPriceA(); //A级单价
				upPriceA = price.subtract(upPriceA).multiply(new BigDecimal(total));
				introUserA=upMemberUserDO.getId();
			}else if (upMemberUserDO.getLevel()=='C'){
				BigDecimal multiplyC = product.getPriceC(); //C级单价
				multiplyC = price.subtract(multiplyC).multiply(new BigDecimal(total));
				introUserC=upMemberUserDO.getId();
				MemberUserDO memberUserDO = memberUserDao.get(upMemberUserDO.getIntroUser());
				if(memberUserDO!=null&&memberUserDO.getLevel()=='B'&&memberUserDO.getDisabled()==0){
					BigDecimal multiplyB = product.getPriceB(); //B级单价
					upPriceB = multiplyC.subtract(multiplyB).multiply(new BigDecimal(total));
					introUserB=memberUserDO.getId();
					//查看B级有没有A级
					MemberUserDO memberUserDOA = memberUserDao.get(memberUserDO.getIntroUser());
					if(memberUserDOA!=null&&memberUserDOA.getLevel()=='A'&&memberUserDOA.getDisabled()==0){
						BigDecimal multiplyA = product.getPriceA(); //B级单价
						//upPriceA = product.getPriceA(); //A级单价
						upPriceA= multiplyB.subtract(multiplyA).multiply(new BigDecimal(total));
						introUserA=memberUserDOA.getId();
					}
				}else if(memberUserDO!=null&&memberUserDO.getLevel()=='A'&&memberUserDO.getDisabled()==0){
					upPriceA = product.getPriceA(); //A级单价
					upPriceA  = multiplyC.subtract(upPriceA).multiply(new BigDecimal(total));
					introUserA=memberUserDO.getId();
				}
			}
		}
		//往分佣表插入数据
		if(upPriceA!=null){
			insertOrderCom(order, upPriceA, introUserA);
		}
		if(upPriceB!=null){
			insertOrderCom(order, upPriceB, introUserB);
		}
		if(upPriceC!=null){
			insertOrderCom(order, upPriceC, introUserC);
		}
	}

	private BigDecimal goodsPrice(MemberUserDO user, Price product, BigDecimal price) {
		/*if(user.getLevel()==0){
			price = product.getPriceA(); //单价
		}else if (user.getLevel()=='B'){
			price = product.getPriceB(); //单价
		}else if (user.getLevel()=='C'){
			price = product.getPriceC(); //单价
		}else {
			price = product.getPrice();
		}*/
		return price;
	}

	private void insertOrderCom(OrderOrderDO order, BigDecimal priceA, String introUserA) {
		OrderComDO orderComDO = new OrderComDO();
		orderComDO.setComPrice(priceA);
		orderComDO.setCreateAt(new Date());
		orderComDO.setDelFlag(0);
		orderComDO.setId(UuidUtil.get32UUID());
		orderComDO.setOrderId(order.getId());
		orderComDO.setStatus(0);
		orderComDO.setUserId(introUserA);
		orderComDao.save(orderComDO);
		
	}


	/*商品详情添加订单，仅限于 普通、秒杀、9.9专区商品*/
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R addGoodsOrder(Map<String,Object> paramMap) {
		Integer type = Integer.valueOf(paramMap.get("type").toString());  //0：普通商品，1：秒杀商品，2:9.9商品
		String productId = paramMap.get("productId").toString();   //规格id
		String id = paramMap.get("id").toString();       //type为0时传商品id，type为1时传秒杀id，type为2时传9.9专区id
		Integer total = Integer.valueOf(paramMap.get("total").toString());  //商品数量
		String userId = paramMap.get("userId").toString();  //用户id
		String buyerMsg = paramMap.get("buyerMsg").toString();  //留言
		String couponId = paramMap.get("couponId").toString();  //优惠券id
		BigDecimal postFee = new BigDecimal(paramMap.get("postFee").toString());  //邮费
		String addressId = paramMap.get("addressId").toString();  //收货地址
		MemberUserDO user = memberUserDao.get(userId);
		Date date = new Date();

		//订单表
		OrderOrderDO order = new OrderOrderDO();
		String order_sn = String.valueOf(Id.next());  //订单号
		order.setOrderSn(order_sn);
		order.setId(UuidUtil.get32UUID());
		order.setCreateAt(date);
		order.setUpdateAt(date);
		order.setUserId(userId);
		order.setBuyerMsg(buyerMsg);
		order.setBuyerNick(user.getName());
		order.setDelFlag(0);
		order.setExport(0);
		order.setPostFee(postFee);
		order.setSee(0);

		//订单配送表
		MemberAddressDO memberAddress = memberAddressDao.get(addressId);
		OrderShippingDO shipping = new OrderShippingDO();
		shipping.setId(UuidUtil.get32UUID());
		shipping.setOrderId(order.getId());
		shipping.setReceiverName(memberAddress.getFullName());
		shipping.setReceiverPhone(memberAddress.getPhone());
		shipping.setReceiverProvince(memberAddress.getProvince());
		shipping.setReceiverCity(memberAddress.getCity());
		shipping.setReceiverCounty(memberAddress.getCounty());
		shipping.setReceiverTown(memberAddress.getTown());
		shipping.setReceiverAddress(memberAddress.getAddress());
		shipping.setCreateAt(date);
		shipping.setUpdateAt(date);
		shipping.setDelFlag(0);
		orderShippingDao.save(shipping);

		//订单详情表
		BigDecimal price = new BigDecimal(0);
		BigDecimal goodsPrice = new BigDecimal(0);

		String goodId = id;
		//判库存，填价格，定返佣，改销量
		GoodsProductDO product = goodsProductDao.get(productId);
		int stock = product.getStock();   //规格库存
		if (type == 1) {  //秒杀商品
			GoodsSpikeDO spikeDO = goodsSpikeDao.get(id);
			goodId = spikeDO.getGoodsId();
			//price = goodsPrice(user, spikeDO, price);
			goodsPrice = price.multiply(new BigDecimal(total));//总价
			//返佣
			rakeBack(user, order, total, spikeDO, price);
			/*priceA = spikeDO.getPriceA().multiply(new BigDecimal(total));  //一级返佣
			priceB = spikeDO.getPriceB().multiply(new BigDecimal(total));  //二级返佣
			priceC = spikeDO.getPriceC().multiply(new BigDecimal(total));  //二级返佣
*/			int spikeNumSale = spikeDO.getNumSale()+total;  //新秒杀销量
			int spikeStoke = spikeDO.getStock();    //旧库存
			int newSpikeStock = spikeStoke-total;   //新库存
			Map<String,Object> spikeMap = new HashMap<String,Object>();
			if (newSpikeStock < 0) {
				newSpikeStock = 0;
			}
			spikeMap.put("id",id);
			spikeMap.put("newStock", newSpikeStock);
			spikeMap.put("oldStock", spikeStoke);
			spikeMap.put("spikeNumSale", spikeNumSale);
			int n = goodsSpikeDao.updateByOld(spikeMap);
			if (n == 0) {
				goodsProductDao.error(spikeMap);
			}
		} else if (type == 2) {   //9.9商品
			GoodsNineDO nineDO = goodsNineDao.get(id);
			goodId = nineDO.getGoodsId();
			//price = goodsPrice(user, nineDO, price);
			goodsPrice = price.multiply(new BigDecimal(total));//总价
			//返佣
			rakeBack(user, order, total, nineDO, price);
			/*priceA = nineDO.getPriceA().multiply(new BigDecimal(total));  //一级返佣
			priceB = nineDO.getPriceB().multiply(new BigDecimal(total));  //二级返佣
			priceC = nineDO.getPriceC().multiply(new BigDecimal(total));  //二级返佣
*/			int nineNumSale = nineDO.getNumSale()+total;  //新专区销量
			int nineStoke = nineDO.getStock();    //旧库存
			int newNineStock = nineStoke-total;   //新库存
			Map<String,Object> nineMap = new HashMap<String,Object>();
			if (newNineStock < 0) {
				newNineStock = 0;
			}
			nineMap.put("id",id);
			nineMap.put("newStock", newNineStock);
			nineMap.put("oldStock", nineStoke);
			nineMap.put("nineNumSale", nineNumSale);
			int n = goodsNineDao.updateByOld(nineMap);
			if (n == 0) {
				goodsProductDao.error(nineMap);
			}
		} else if (type == 0) {  //普通商品
			price = goodsProductDao.get(productId).getPrice(); //单价
			goodsPrice = price.multiply(new BigDecimal(total));//总价
			//返佣
			//rakeBack(user, order, total, product, price);
			/*priceA = product.getPriceA().multiply(new BigDecimal(total));  //一级返佣
			priceB = product.getPriceB().multiply(new BigDecimal(total));  //一级返佣
			priceC = product.getPriceC().multiply(new BigDecimal(total));  //二级返佣
*/		}else if(type == 5){
			price = goodsProductDao.get(productId).getPrice(); //单价
			goodsPrice = price.multiply(new BigDecimal(total));//总价
			//审批订单表加入数据
			saveOrderReview(userId, order);
		}

		OrderDetailDO detailDO = new OrderDetailDO();
		detailDO.setId(UuidUtil.get32UUID());
		detailDO.setGoodsId(goodId);
		detailDO.setOrderId(order.getId());
		detailDO.setProductId(productId);
		detailDO.setPrice(price);
		detailDO.setAllPrice(goodsPrice);
		detailDO.setComent(0);
		detailDO.setCreateAt(date);
		detailDO.setDelFlag(0);
		detailDO.setTotal(total);
		orderDetailDao.save(detailDO);
		//修改商品库存、销量
		Map<String,Object> proMap = new HashMap<String,Object>();
		int newStock = stock-total;
		if (newStock < 0) {
			newStock = 0;
		}
		proMap.put("id",productId);
		proMap.put("newStock", newStock);
		proMap.put("oldStock", stock);
		int n = goodsProductDao.updateByOld(proMap);
		if (n == 0) {
			goodsProductDao.error(proMap);
		}
		//销量添加
		GoodsGoodsDO goods = goodsGoodsDao.get(goodId);
		int numSale = 0;
		if (goods.getNumSale() != null) {
			numSale = goods.getNumSale();
		}
		int num_sale = numSale+total;
		GoodsGoodsDO good = new GoodsGoodsDO();
		good.setId(goodId);
		good.setNumSale(num_sale);
		goodsGoodsDao.update(good);

		BigDecimal allPrice = new BigDecimal(0);
		MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
		if (memberCouponDO != null) {
			BigDecimal couponMoney = memberCouponDO.getMoney();  //优惠金额
			allPrice = goodsPrice.add(postFee).subtract(couponMoney);  //订单总金额
			//修改用户优惠券
			MemberCouponDO couponDO = new MemberCouponDO();
			couponDO.setId(memberCouponDO.getId());
			couponDO.setStatus(1);
			couponDO.setOrderAt(date);
			couponDO.setUpdateAt(date);
			couponDO.setOrderId(order.getId());
			memberCouponDao.update(couponDO);
		} else {
			allPrice = goodsPrice.add(postFee);  //订单总金额
		}

		/*//开始分销
		String intorId = user.getIntroUser();
		for (int i=1; i<3; i++) {
			if (intorId == null || "".equals(intorId)) {
				break;
			}
			MemberUserDO productUser = memberUserDao.get(intorId);
			if (productUser == null) {
				break;
			}
			int disbled = productUser.getDisabled();
			if (disbled == 1) {  //如果账号被冻结
				i--;
				intorId = productUser.getIntroUser();
				continue;
			}

			BigDecimal money = new BigDecimal(0);
			if (i == 1) {
				money = priceA;
			} else if (i == 2) {
				money = priceB;
			}
			OrderComDO comDO = new OrderComDO();
			comDO.setId(UuidUtil.get32UUID());
			comDO.setCreateAt(date);
			comDO.setDelFlag(0);
			comDO.setOrderId(order.getId());
			comDO.setComPrice(money);
			comDO.setStatus(0);
			comDO.setUpdateAt(date);
			comDO.setUserId(intorId);
			orderComDao.save(comDO);
			intorId = productUser.getIntroUser();
		}*/
		//order_order补充
		order.setShopId(goods.getShopId());
		order.setPayment(allPrice);
		order.setCouponId(couponId);
		order.setOrdertype(type);
		order.setStatus(1);
		order.setComent(0);
		order.setPayNum(KitUtil.getOrderCode());
		orderOrderDao.save(order);
		Map<String,Object> map = new HashMap<>();
		map.put("allPrice",allPrice);
		map.put("payNum",order.getPayNum());
		return R.ok().put("data",map);
	}

	private void saveOrderReview(String userId, OrderOrderDO order) {
		OrderReviewDO orderReviewDO = new OrderReviewDO();
		//采购员
		orderReviewDO.setOrderId(order.getId());
		orderReviewDO.setId(UuidUtil.get32UUID());
		orderReviewDO.setStatus(1);
		orderReviewDO.setDelFlag(0);
		orderReviewDO.setCaAt(new Date());
		orderReviewDO.setUserId(userId);
		MallCompanyUserDO byUserId = mallCompanyUserDao.getByUserId(userId);
		orderReviewDO.setCreateId(byUserId.getCreateId());
		orderReviewDO.setLevel(0);
		orderReviewDao.save(orderReviewDO);
		//审核员
		orderReviewDO.setLevel(1);
		orderReviewDO.setId(UuidUtil.get32UUID());
		MallCompanyUserDO mallCompanyUserDO = mallCompanyUserDao.get(byUserId.getParentId());
		orderReviewDO.setUserId(mallCompanyUserDO.getUserId());
		orderReviewDO.setStatus(0);
		orderReviewDao.save(orderReviewDO);
	}

	/*购买砍价商品，创建订单*/
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R addBargainGoodsOrder(Map<String,Object> paramMap) {
		String productId = paramMap.get("productId").toString();   //规格id
		String bargainId = paramMap.get("bargainId").toString();       //砍价id
		Integer total = Integer.valueOf(paramMap.get("total").toString());  //商品数量，固定为 1
		String userId = paramMap.get("userId").toString();  //用户id
		String buyerMsg = paramMap.get("buyerMsg").toString();  //留言
		String couponId = paramMap.get("couponId").toString();  //优惠券id
		BigDecimal postFee = new BigDecimal(paramMap.get("postFee").toString());  //邮费
		String addressId = paramMap.get("addressId").toString();  //收货地址
		MemberUserDO user = memberUserDao.get(userId);
		Date date = new Date();
		GoodsBargainDO goodsBargainDO = goodsBargainDao.get(bargainId);
		String goodsId = goodsBargainDO.getGoodsId();

		//订单表
		OrderOrderDO order = new OrderOrderDO();
		String order_sn = String.valueOf(Id.next());  //订单号
		order.setOrderSn(order_sn);
		order.setId(UuidUtil.get32UUID());
		order.setCreateAt(date);
		order.setUpdateAt(date);
		order.setUserId(userId);
		order.setBuyerMsg(buyerMsg);
		order.setBuyerNick(user.getName());
		order.setDelFlag(0);
		order.setExport(0);
		order.setPostFee(postFee);

		//砍价订单详情
		OrderBargainDO bargainDO = new OrderBargainDO();
		bargainDO.setId(UuidUtil.get32UUID());
		bargainDO.setOrderId(order.getId());
		bargainDO.setDelFlag(0);
		bargainDO.setPrice(goodsBargainDO.getPrice());
		bargainDO.setMinPrice(goodsBargainDO.getMinPrice());
		bargainDO.setMaxPrice(goodsBargainDO.getMaxPrice());
		bargainDO.setPriceA(goodsBargainDO.getPriceA());
		bargainDO.setPriceB(goodsBargainDO.getPriceB());
		bargainDO.setPriceC(goodsBargainDO.getPriceC());
		bargainDO.setStartAt(date);
		Date endAt = DateUtils.addHourOfDate(date,goodsBargainDO.getTime());
		bargainDO.setEndAt(endAt);
		orderBargainDao.save(bargainDO);

		//订单配送表
		MemberAddressDO memberAddress = memberAddressDao.get(addressId);
		OrderShippingDO shipping = new OrderShippingDO();
		shipping.setId(UuidUtil.get32UUID());
		shipping.setOrderId(order.getId());
		shipping.setReceiverName(memberAddress.getFullName());
		shipping.setReceiverPhone(memberAddress.getPhone());
		shipping.setReceiverProvince(memberAddress.getProvince());
		shipping.setReceiverCity(memberAddress.getCity());
		shipping.setReceiverCounty(memberAddress.getCounty());
		shipping.setReceiverTown(memberAddress.getTown());
		shipping.setReceiverAddress(memberAddress.getAddress());
		shipping.setCreateAt(date);
		shipping.setUpdateAt(date);
		shipping.setDelFlag(0);
		orderShippingDao.save(shipping);

		//订单详情表
		BigDecimal price = new BigDecimal(0);
		BigDecimal goodsPrice = new BigDecimal(0);
		BigDecimal priceA = new BigDecimal(0);
		BigDecimal priceB = new BigDecimal(0);
		BigDecimal priceC = new BigDecimal(0);
		//判库存，填价格，定返佣，改销量
		GoodsProductDO product = goodsProductDao.get(productId);
		int stock = product.getStock();   //规格库存
		//price = goodsPrice(user, goodsBargainDO, price);//单价
		goodsPrice = price.multiply(new BigDecimal(total));//总价
		
		//返佣
		rakeBack(user, order, total, goodsBargainDO, price);
		/*priceA = goodsBargainDO.getPriceA().multiply(new BigDecimal(total));  //一级返佣
		priceB = goodsBargainDO.getPriceB().multiply(new BigDecimal(total));  //二级返佣
		priceC = goodsBargainDO.getPriceC().multiply(new BigDecimal(total));  //二级返佣
*/		int bargainNumSale = goodsBargainDO.getNumSale()+total;  //新秒杀销量
		int bargainStock = goodsBargainDO.getStock();    //旧秒杀库存
		int newBarStock = bargainStock-total;   //新秒杀库存
		Map<String,Object> spikeMap = new HashMap<String,Object>();
		if (newBarStock < 0) {
			newBarStock = 0;
		}
		spikeMap.put("id",bargainId);
		spikeMap.put("newStock", newBarStock);
		spikeMap.put("oldStock", bargainStock);
		spikeMap.put("numSale", bargainNumSale);
		int n = goodsBargainDao.updateByOld(spikeMap);
		if (n == 0) {
			goodsProductDao.error(spikeMap);
		}

		OrderDetailDO detailDO = new OrderDetailDO();
		detailDO.setId(UuidUtil.get32UUID());
		detailDO.setGoodsId(goodsId);
		detailDO.setOrderId(order.getId());
		detailDO.setProductId(productId);
		detailDO.setPrice(price);
		detailDO.setAllPrice(goodsPrice);
		detailDO.setComent(0);
		detailDO.setCreateAt(date);
		detailDO.setDelFlag(0);
		detailDO.setTotal(total);
		orderDetailDao.save(detailDO);
		//修改商品库存、销量
		Map<String,Object> proMap = new HashMap<String,Object>();
		int newStock = stock-total;
		if (newStock < 0) {
			newStock = 0;
		}
		proMap.put("id",productId);
		proMap.put("newStock", newStock);
		proMap.put("oldStock", stock);
		int m = goodsProductDao.updateByOld(proMap);
		if (m == 0) {
			goodsProductDao.error(proMap);
		}
		//销量添加
		GoodsGoodsDO goods = goodsGoodsDao.get(goodsId);
		int numSale = 0;
		if (goods.getNumSale() != null) {
			numSale = goods.getNumSale();
		}
		int num_sale = numSale+total;
		GoodsGoodsDO good = new GoodsGoodsDO();
		good.setId(goodsId);
		good.setNumSale(num_sale);
		goodsGoodsDao.update(good);

		BigDecimal allPrice = new BigDecimal(0);
		MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
		if (memberCouponDO != null) {
			BigDecimal couponMoney = memberCouponDO.getMoney();  //优惠金额
			allPrice = goodsPrice.add(postFee).subtract(couponMoney);  //订单总金额
			//修改用户优惠券
			MemberCouponDO couponDO = new MemberCouponDO();
			couponDO.setId(memberCouponDO.getId());
			couponDO.setStatus(1);
			couponDO.setOrderAt(date);
			couponDO.setUpdateAt(date);
			couponDO.setOrderId(order.getId());
			memberCouponDao.update(couponDO);
		} else {
			allPrice = goodsPrice.add(postFee);  //订单总金额
		}

		/*//开始分销
		String intorId = user.getIntroUser();
		for (int i=1; i<3; i++) {
			if (intorId == null || "".equals(intorId)) {
				break;
			}
			MemberUserDO productUser = memberUserDao.get(intorId);
			if (productUser == null) {
				break;
			}
			int disbled = productUser.getDisabled();
			if (disbled == 1) {  //如果账号被冻结,找下一个
				i--;
				intorId = productUser.getIntroUser();
				continue;
			}

			BigDecimal money = new BigDecimal(0);
			if (i == 1) {
				money = priceA;
			} else if (i == 2) {
				money = priceB;
			}
			OrderComDO comDO = new OrderComDO();
			comDO.setId(UuidUtil.get32UUID());
			comDO.setCreateAt(date);
			comDO.setDelFlag(0);
			comDO.setOrderId(order.getId());
			comDO.setComPrice(money);
			comDO.setStatus(0);
			comDO.setUpdateAt(date);
			comDO.setUserId(intorId);
			orderComDao.save(comDO);
			intorId = productUser.getIntroUser();
		}*/
		//order_order补充
		order.setPayment(allPrice);
		order.setCouponId(couponId);
		order.setOrdertype(3);
		order.setStatus(0);
		order.setComent(0);
		orderOrderDao.save(order);
		return R.ok().put("data",order);
	}





	@Override
	public PageInfo<Map<String,Object>> getOrderListByStatus(Map<String,Object> paramMap) {
		PageHelperUtils.page(paramMap);
		String type = paramMap.get("type").toString(); //类型
		String userId = paramMap.get("userId").toString(); //会员id
		String [] status = new String[10];
		if (type.equals("1")) { //待支付
			status[0] = "1";
		} else if (type.equals("2")) { //待发货
			status[0] = "3";
		} else if (type.equals("3")) { //待收货
			status[0] = "4";
		} else if (type.equals("4")) { //待评价
			status[0] = "7";
		} else if (type.equals("5")) {  //问题订单
			status[0] = "5";
			status[1] = "6";
			status[2] = "8";
		} else if (type.equals("0")) { //全部
			//status[0] = "0";
			status[0] = "1";
			status[1] = "2";
			status[2] = "3";
			status[3] = "4";
			status[4] = "7";
			status[5] = "8";
			/*status[9] = "9";
			status[10] = "10";*/
		}
		paramMap.put("status", status);
		List<Map<String,Object>> list = orderOrderDao.getOrderListByStatus(paramMap);
		for (Map<String,Object> map : list) {
			Date create_at = MapUtil.getDate(map, "create_at");
			String format = DateUtil.format(create_at, DateUtils.YYYY_MM_DD_HH_MM_SS);
			map.put("create_at",format);
			String orderId = map.get("id").toString();
			List<Map<String,Object>> detailList = orderDetailDao.getByOrderId(orderId);
			map.put("detailList",detailList);

		}
		PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int setStatusOrder (Map<String,Object> paramMap) {
		String userId = paramMap.get("userId").toString();
		String orderId = paramMap.get("orderId").toString();
		String type = paramMap.get("type").toString();
		Map<String,Object> map = new HashMap<String,Object>();
		Date date = new Date();
		map.put("userId",userId);
		map.put("id",orderId);
		if ("8".equals(type)) {   //取消订单
			map.put("status","1");
			List<OrderOrderDO> orderList = orderOrderDao.list(map);
			if (orderList.size() == 0) {
				return 1;
			}
			OrderOrderDO order = new OrderOrderDO();
			order.setId(orderId);
			order.setStatus(8);
			orderOrderDao.update(order);
			orderComDao.removeCom(orderId);
			List<Map<String, Object>> byOrderId = orderDetailDao.getByOrderId(orderId);
			if(byOrderId.size()>0){
				for (Map<String, Object> detailMap : byOrderId) {
					GoodsProductDO goodsProductDO = goodsProductDao.get(detailMap.get("productId").toString());
					goodsProductDO.setStock(goodsProductDO.getStock()+Integer.parseInt(detailMap.get("total").toString()));
					goodsProductDao.update(goodsProductDO);
				}
			}
		} else if ("7".equals(type)) {  //收货
			map.put("status","4");
			List<OrderOrderDO> orderList = orderOrderDao.list(map);
			if (orderList.size() == 0) {
				return 1;
			}
			OrderOrderDO order = orderOrderDao.get(orderId);
			//OrderOrderDO order = new OrderOrderDO();
			order.setId(orderId);
			order.setStatus(7);
			order.setUpdateAt(date);
			order.setReceivingAt(date);
			order.setEndAt(date);


			orderOrderDao.update(order);
			ShopShopDO shopShopDO = shopShopDao.get(order.getShopId());
			shopShopDO.setMoney(order.getPayment());
			shopShopDO.setAllMoney(order.getPayment());
			shopShopDao.update(shopShopDO);
		} /*else if ("5".equals(type)) {  //退货
			map.put("status","4");
			List<OrderOrderDO> orderList = orderOrderDao.list(map);
			if (orderList.size() == 0) {
				return 1;
			}
			OrderOrderDO order = new OrderOrderDO();
			order.setId(orderId);
			order.setStatus(5);
			orderOrderDao.update(order);
		}*/
		return 0;
	}

	/*去评论*/
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int setComent(Map<String,Object> paramMap) {
		String userId = paramMap.get("userId").toString();
		String orderId = paramMap.get("orderId").toString();
		Date date = new Date();
		List<Map<String,Object>> comentList = (List<Map<String,Object>>)(paramMap.get("comentList"));
		for (Map<String,Object> comentMap : comentList) {
			int start = new Integer(comentMap.get("start").toString());
			String content = comentMap.get("content").toString();
			String detailId = comentMap.get("detailId").toString();
			String imgurls = comentMap.get("imgurls").toString();
			if (StringUtils.isBlank(content)) {
				return 1;
			}
			//评论表
			OrderComentDO comentDO = new OrderComentDO();
			comentDO.setId(UuidUtil.get32UUID());
			comentDO.setContent(content);
			comentDO.setDetailId(detailId);
			comentDO.setStar(start);
			comentDO.setDisply(0);
			comentDO.setCreateAt(date);
			comentDO.setUserId(userId);
			comentDO.setImgurls(imgurls);
			orderComentDao.save(comentDO);
			//修改detail表
			OrderDetailDO detailDO = new OrderDetailDO();
			detailDO.setId(detailId);
			detailDO.setComent(1);
			orderDetailDao.update(detailDO);
			//修改商品评论量
			OrderDetailDO orderDetailDO = orderDetailDao.get(detailId);
			String goodsId = orderDetailDO.getGoodsId();
			GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(goodsId);
			int newNum = goodsGoodsDO.getNumComment()+1;
			GoodsGoodsDO goodsDO = new GoodsGoodsDO();
			goodsDO.setId(goodsId);
			goodsDO.setNumComment(newNum);
			goodsGoodsDao.update(goodsDO);

		}
		OrderOrderDO orderOrderDO = new OrderOrderDO();
		orderOrderDO.setId(orderId);
		orderOrderDO.setComent(1);
		orderOrderDao.update(orderOrderDO);
		return 0;
	}

	@Override
	public Map<String,Object> getOrderById(Map<String,Object> paramMap) {
		Map<String,Object> orderMap = orderOrderDao.getOrderById(paramMap);
		List<OrderDetailDO> detailList = orderDetailDao.list(paramMap);
		List<Map<String,Object>> goodsList = new ArrayList<Map<String,Object>>();
		BigDecimal goodsAllPrice = new BigDecimal(0);
		int allNumber = 0;
		for (OrderDetailDO detailDO : detailList) {
			Map<String,Object> map = new HashMap<String,Object>();
			String goodsId = detailDO.getGoodsId();
			String productId = detailDO.getProductId();
			BigDecimal goodsPrice = detailDO.getPrice();
			BigDecimal total = new BigDecimal(detailDO.getTotal());
			allNumber = allNumber+detailDO.getTotal();
			goodsAllPrice = goodsAllPrice.add(goodsPrice.multiply(total));
			GoodsProductDO productDO = goodsProductDao.get(productId);
			GoodsGoodsDO goodsDO = goodsGoodsDao.get(goodsId);
			map.put("total", total);
			map.put("imgurl", goodsDO.getImgurl());
			map.put("goodsName",goodsDO.getName());
			map.put("goodsPrice", goodsPrice);
			map.put("spec", productDO.getSpec());
			map.put("goodsId",goodsDO.getId());
			map.put("detailId",detailDO.getId());
			goodsList.add(map);
		}
		orderMap.put("allNumber",allNumber);
		orderMap.put("goodsList",goodsList);
		orderMap.put("goodsAllPrice", goodsAllPrice);
		//查询优惠券金额
		String coupon_id = orderMap.get("coupon_id").toString();
		if (coupon_id.equals("")) {
			orderMap.put("couponPrice", "0");
		} else {
			MemberCouponDO couponDO = memberCouponDao.get(coupon_id);
			orderMap.put("couponPrice",couponDO.getMoney());
		}
		return orderMap;
	}

	@Override
	public Map<String,Object> getKOrderById(Map<String,Object> paramMap) {
		Map<String,Object> orderMap = orderOrderDao.getOrderById(paramMap);
		List<OrderDetailDO> detailList = orderDetailDao.list(paramMap);
		List<Map<String,Object>> goodsList = new ArrayList<Map<String,Object>>();
		BigDecimal goodsAllPrice = new BigDecimal(0);
		int allNumber = 0;
		for (OrderDetailDO detailDO : detailList) {
			Map<String,Object> map = new HashMap<String,Object>();
			String goodsId = detailDO.getGoodsId();
			String productId = detailDO.getProductId();
			BigDecimal goodsPrice = detailDO.getPrice();
			BigDecimal total = new BigDecimal(detailDO.getTotal());
			allNumber = allNumber+detailDO.getTotal();
			goodsAllPrice = goodsAllPrice.add(goodsPrice.multiply(total));
			GoodsProductDO productDO = goodsProductDao.get(productId);
			GoodsGoodsDO goodsDO = goodsGoodsDao.get(goodsId);
			map.put("total", total);
			map.put("imgurl", goodsDO.getImgurl());
			map.put("goodsName",goodsDO.getName());
			map.put("goodsPrice", goodsPrice);
			map.put("spec", productDO.getSpec());
			map.put("goodsId",goodsDO.getId());
			map.put("detailId",detailDO.getId());
			goodsList.add(map);
		}
		orderMap.put("allNumber",allNumber);
		orderMap.put("goodsList",goodsList);
		orderMap.put("goodsAllPrice",goodsAllPrice);
		//查询优惠券金额
		String coupon_id = orderMap.get("coupon_id").toString();
		if (coupon_id.equals("")) {
			orderMap.put("couponPrice","0");
		} else {
			MemberCouponDO couponDO = memberCouponDao.get(coupon_id);
			orderMap.put("couponPrice",couponDO.getMoney());
		}
		//查询帮忙砍价人
		List<Map<String,Object>> userList = orderBargainUserDao.getUserByOrder(paramMap);
		orderMap.put("userList", userList);
		return orderMap;
	}

	@Override
	public List<Map<String,Object>> getOrderList(Map<String, Object> map){
		return orderOrderDao.getOrderList(map);
	}

	@Override
	public int getOrderListCount(Map<String, Object> map) {
		return orderOrderDao.getOrderListCount(map);
	}

	/**
	 * 添加物流
	 * @param order
	 * @return
	 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int addShipping(OrderOrderDO order) {
		Date date = new Date();
		ShopExpressCodeDO codeDO = shopExpressCodeDao.queryByCode(order.getShippingName());
		ShopExpressMessageDO messageDO = shopExpressMessageDao.queryByOrderId(order.getId());
		if (messageDO==null && codeDO != null){
			order.setStatus(4);
			order.setUpdateAt(date);
			order.setConsignAt(date);
			orderOrderDao.update(order);

			messageDO = new ShopExpressMessageDO();
			messageDO.setId(UuidUtil.get32UUID());
			messageDO.setStatus(0);
			messageDO.setName(codeDO.getName());
//			messageDO.setCode(order.getShippingCode());
			messageDO.setCode(codeDO.getCode());
			messageDO.setExpressId(order.getShippingCode());
			messageDO.setUserId(order.getUserId());
			messageDO.setDelFlag(0);
			messageDO.setOpAt(new Date());
			messageDO.setOrderId(order.getId());
			shopExpressMessageDao.save(messageDO);

			//推送
			/*OrderOrderDO orderOrderDO = orderOrderDao.get(order.getId());
			String userId = orderOrderDO.getUserId();
			List<String> newList = new ArrayList<String>();
			newList.add(userId);
			String content = "您的订单已发货，订单号为："+orderOrderDO.getOrderSn();
			jPushService.checkPush(newList, content, 0, "0");*/
			//发信息
			/*Map<String,Object> shippingMap =orderOrderDao.getOrderById(order.getId());
			String mobile = shippingMap.get("receiver_phone").toString();
			String name = shippingMap.get("name").toString();
			String shippingCode = orderOrderDO.getShippingCode();
			String code = " "+name+"已发货，详情请查询 "+codeDO.getName()+"："+shippingCode+"";
			try {
				JuSms.sendFSms(mobile, code);
			} catch (IOException e) {
				e.printStackTrace();
				return 1;
			}*/
			return 1;
		}
		return 0;
	}

	/**
	 * 修改物流
	 * @param order
	 * @return
	 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int editShipping(OrderOrderDO order) {
		Date date = new Date();
		String orderId = order.getId();
		ShopExpressCodeDO codeDO = shopExpressCodeDao.queryByCode(order.getShippingName());
		ShopExpressMessageDO messageDO = shopExpressMessageDao.queryByOrderId(orderId);
		if (messageDO != null && codeDO != null){
			order.setStatus(4);
			order.setUpdateAt(date);
			order.setConsignAt(date);
			orderOrderDao.update(order);

			//先删除旧信息
			shopExpressMessageDao.remove(messageDO.getId());
			shopExpressDetailsDao.removeByOrderId(orderId);

			ShopExpressMessageDO newMessageDO = new ShopExpressMessageDO();
			newMessageDO.setId(UuidUtil.get32UUID());
			newMessageDO.setStatus(0);
			newMessageDO.setName(codeDO.getName());
//			newMessageDO.setCode(order.getShippingCode());
			newMessageDO.setCode(codeDO.getCode());
			newMessageDO.setExpressId(order.getShippingCode());
			newMessageDO.setUserId(order.getUserId());
			newMessageDO.setDelFlag(0);
			newMessageDO.setOpAt(new Date());
			newMessageDO.setOrderId(order.getId());
			shopExpressMessageDao.save(newMessageDO);

			//推送
			/*OrderOrderDO orderOrderDO = orderOrderDao.get(order.getId());
			String userId = orderOrderDO.getUserId();
			List<String> newList = new ArrayList<String>();
			newList.add(userId);
			String content = "您的订单已发货，订单号为："+orderOrderDO.getOrderSn();
			jPushService.checkPush(newList, content, 0, "0");*/
			return 1;
		}
		return 0;
	}

	@Override
	public Map<String,Object> getHOrderById(String id) {
		return orderOrderDao.getHOrderById(id);
	}

	@Override
	public List<Map<String,Object>> statisticsList(Map<String, Object> map){
		return orderOrderDao.statisticsList(map);
	}

	@Override
	public int statisticsCount(Map<String, Object> map) {
		return orderOrderDao.statisticsCount(map);
	}

	@Override
	public List<Map<String,Object>> getDetailGoods(Map<String, Object> map) {
		return orderOrderDao.getDetailGoods(map);
	}

	@Override
	public int getDetailGoodsCount(Map<String, Object> map) {
		return orderOrderDao.getDetailGoodsCount(map);
	}

	@Override
	public List<Map<String,Object>> getKUsers(Map<String, Object> map) {
		return orderOrderDao.getKUsers(map);
	}

	@Override
	public int getKUsersCount(Map<String, Object> map) {
		return orderOrderDao.getKUsersCount(map);
	}


	/*导出excel。改变订单导出状态*/
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public void exportExcel(Map<String,Object> map,List<Map<String,Object>> userList,
							ServletOutputStream out,HttpServletRequest request) {
		//导出excel
		/*if (OrderExcelUtils.exportUserExcel(userList, out) == 1) {
			//改变订单导出状态
			int number = orderOrderDao.updateExportByMap(map);
			//添加导出记录
			Long customId = getUserId();
			String userName = userDao.get(customId).getUsername();  //管理员账号
			OrderExcelRecodeDO recode = new OrderExcelRecodeDO();
			recode.setId(UuidUtil.get32UUID());
			recode.setCreateAt(new Date());
			recode.setUserPhone(userName);
			recode.setNumber(number);
			recode.setIp(IPUtils.getIp(request));
			orderExcelRecodeDao.save(recode);
		}*/
	}

	/*
	* 导入excel表格
	* */
	@Override
	public void importExcel(MultipartFile file, String excelFileName) {
		//1.创建输入流
		try {
			//FileInputStream inputStream = new FileInputStream(file);
			//boolean is03Excel = excelFileName.matches("^.+\\.(?i)(xls)$");
			//1.读取工作簿
			boolean is03Excel = excelFileName.matches("^.+\\.(?i)(xls)$");
			Workbook workbook = is03Excel?new HSSFWorkbook(file.getInputStream()):new XSSFWorkbook(file.getInputStream());
			//Workbook workbook = new HSSFWorkbook(file.getInputStream());
			//2.读取工作表
			Sheet sheet = workbook.getSheetAt(0);
			//3.读取行
			//判断行数大于一,是因为数据从第二行开始插入
			int num = sheet.getPhysicalNumberOfRows();
			if(sheet.getPhysicalNumberOfRows() > 1) {
				//跳过前一行
				for(int k=1;k<sheet.getPhysicalNumberOfRows();k++ ) {
					//读取单元格
					Row row0 = sheet.getRow(k);
					//订单id
					Cell cell0 = row0.getCell(0);
					//cell0.setCellType(Cell.CELL_TYPE_STRING);
					String order_sn =cell0.getStringCellValue().replace("\t","").trim();
					//物流名
					String shipping_name = "";
					Cell cell9 = row0.getCell(1);
					if (cell9 == null) {
						shipping_name = "";
					} else {
						//cell9.setCellType(Cell.CELL_TYPE_STRING);
						shipping_name = cell9.getStringCellValue().replace("\t","").trim();
					}
					//物流单号
					String shipping_code = "";
					Cell cell10 = row0.getCell(2);
					if (cell10 == null) {
						shipping_code = "";
					} else {
						//cell10.setCellType(Cell.CELL_TYPE_STRING);
						shipping_code = cell10.getStringCellValue().replace("\t","").trim();
					}
					if (!("".equals(order_sn.trim()) || "".equals(shipping_name.trim()) || "".equals(shipping_code.trim()))) {
						OrderOrderDO ceOrder = orderOrderDao.getByOrder(order_sn);
						int status = ceOrder.getStatus();
						String id = ceOrder.getId();
						if (status == 6) {
							OrderOrderDO order = new OrderOrderDO();
							order.setId(id);
							order.setShippingName(shipping_name.trim());
							order.setShippingCode(shipping_code.trim());
							order.setUserId(ceOrder.getUserId());
							addShipping(order);
						}
					}
				}
			}
			workbook.close();
			//inputStream.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*后台退货列表*/
	@Override
	public List<Map<String,Object>> getBackOrderList(Map<String, Object> map){
		return orderOrderDao.getBackOrderList(map);
	}

	@Override
	public int getBackOrderListCount(Map<String, Object> map) {
		return orderOrderDao.getBackOrderListCount(map);
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int backOrder(OrderOrderDO order) {
		String orderId = order.getId();
		int status = order.getStatus();
		order.setUpdateAt(new Date());
		OrderOrderDO orderOrderDO = orderOrderDao.get(orderId);
		if (5 != orderOrderDO.getStatus()) {
			return 0;
		}
		if (status == 6) {  //确认
			orderOrderDao.update(order);
			orderComDao.updateByOrderId(orderId);
			//销量和库存恢复原状
			Map<String,Object> mm = new HashMap<>();
			mm.put("orderId",orderId);
			List<OrderDetailDO> detailList = orderDetailDao.list(mm);
			for (OrderDetailDO detail : detailList) {
				String goodsId = detail.getGoodsId();
				String productId = detail.getProductId();
				int total = detail.getTotal();
				//库存添加
				GoodsProductDO pr = goodsProductDao.get(productId);
				GoodsProductDO pro = new GoodsProductDO();
				int newStock = pr.getStock()+total;
				pro.setId(productId);
				pro.setStock(newStock);
				goodsProductDao.update(pro);
				//销量减去
				GoodsGoodsDO goods = goodsGoodsDao.get(goodsId);
				int num_sale = goods.getNumSale()-total;
				GoodsGoodsDO good = new GoodsGoodsDO();
				good.setId(goodsId);
				good.setNumSale(num_sale);
				goodsGoodsDao.update(good);
			}
		} else if (status == 4){   //驳回
			orderOrderDao.update(order);
			orderBackDao.removeByOrder(orderId);
		}
		return 1;
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int backGood(Map<String,Object> paramMap) {
		Date date = new Date();
		String id = paramMap.get("id").toString();
		/*String expressName = paramMap.get("expressName").toString();
		String expressCode = paramMap.get("expressCode").toString();*/
		String reason = paramMap.get("reason").toString();

		//修改订单表
		OrderOrderDO order = new OrderOrderDO();
		order.setId(id);
		order.setStatus(5);
		order.setPayAt(date);
		order.setUpdateAt(date);
		orderOrderDao.update(order);
		//添加退货记录
		OrderBackDO orderBackDO = new OrderBackDO();
		orderBackDO.setId(UuidUtil.get32UUID());
		orderBackDO.setOrderId(id);
		/*orderBackDO.setExpressName(expressName);
		orderBackDO.setExpressCode(expressCode);*/
		orderBackDO.setReason(reason);
		orderBackDO.setCreateAt(date);
		orderBackDO.setUpdateAt(date);
		orderBackDO.setDelFlag(0);
		orderBackDao.save(orderBackDO);

		//推送
		/*List<String> sList = new ArrayList<String>();
		OrderOrderDO orderOrderDO = orderOrderDao.get(id);
		Object oneId = orderOrderDO.getUserH();
		Object twoId = orderOrderDO.getUserL();
		if (oneId != null && !("".equals(oneId))) {
			sList.add(oneId.toString());
			if (twoId != null && !("".equals(twoId))) {
				sList.add(twoId.toString());
			}
			String content = "您提交的订单已经申请退货，订单号为："+orderOrderDO.getOrderSn();
			jPushService.checkPush(sList, content, 0, "0");
		}*/
		return 1;
	}

	@Override
	public OrderOrderDO getByOrder(String orderSn) {
		return orderOrderDao.getByOrder(orderSn);
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R removeOrder(Map<String, Object> map) {
		String userId = map.get("userId").toString();
		List<String> orderIdList = (List<String>)(map.get("orderIdList"));
		MemberUserDO user = memberUserDao.get(userId);
		if (user == null) {
			return R.error("会员信息错误");
		}

		for (String orderId : orderIdList) {
			OrderOrderDO orderOrderDO = orderOrderDao.get(orderId);
			int status = orderOrderDO.getStatus();
			if (status == 7||status==1 ) {
				OrderOrderDO order = new OrderOrderDO();
				order.setId(orderId);
				order.setDelFlag(1);
				orderOrderDao.update(order);
			}
			List<Map<String, Object>> byOrderId = orderDetailDao.getByOrderId(orderId);
			if(byOrderId.size()>0){
				for (Map<String, Object> detailMap : byOrderId) {
					GoodsProductDO goodsProductDO = goodsProductDao.get(detailMap.get("productId").toString());
					goodsProductDO.setStock(goodsProductDO.getStock()+Integer.parseInt(detailMap.get("total").toString()));
					goodsProductDao.update(goodsProductDO);
				}
			}
		}

		return R.ok();
	}

    @Override
    public R getOrderNumByStatus(Map<String, Object> params) {
		Map<String,Object> map = new HashMap<>();

		//0：砍价中，1：待支付，2：拼团中，3：待发货，4：待收货，5：退货中，6.退货成功，7：订单完成，8：订单取消，9：砍价失败，10：拼团失败

		String [] status = new String[10];
		status[0] = "1";
		params.put("status", status);
		int payNum = orderOrderDao.getOrderListByStatus(params).size();
		status[0] = "3";
		int faNum = orderOrderDao.getOrderListByStatus(params).size();
		status[0] = "4";
		int shouNum = orderOrderDao.getOrderListByStatus(params).size();
		params.put("type","4");
		status[0] = "7";
		int pingNum = orderOrderDao.getOrderListByStatus(params).size();
		params.remove("type");
		status[0] = "5";
		status[1] = "6";
		status[2] = "8";
		int errorNum = orderOrderDao.getOrderListByStatus(params).size();
		map.put("payNum", payNum);   //待支付
		map.put("faNum", faNum);   //待发货
		map.put("shouNum", shouNum);   //待收货
		map.put("pingNum", pingNum);   //待评价
		map.put("errorNum", errorNum);   //错误订单

		return R.ok().put("data",map);
    }

    @Override
    public R confirmGoodsOrder(Map<String, Object> paramMap) {

		GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(paramMap.get("goodsId").toString());
		GoodsProductDO goodsProductDO = goodsProductDao.get(paramMap.get("productId").toString());
		int total = Integer.parseInt(paramMap.get("total").toString());
		MallShopUserDO mallShopUserDO = mallShopUserDao.get(goodsGoodsDO.getShopId());
		Map<String,Object> map = new HashMap<>();
		map.putAll(paramMap);
		map.put("goodsName",goodsGoodsDO.getName());
		map.put("goodsImg",goodsGoodsDO.getImgurl());
		map.put("price",goodsProductDO.getPrice());
		map.put("spec",goodsProductDO.getName());
		map.put("allPrice",goodsProductDO.getPrice().multiply(new BigDecimal(total)));
		map.put("costMoney", goodsGoodsDO.getCostMoney());
		if(mallShopUserDO!=null){
			map.put("shopName",mallShopUserDO.getName());
		}else{
			map.put("shopName","");
		}

		BigDecimal postFee = goodsGoodsDO.getPostFee();
		if(postFee==null){
			postFee= new BigDecimal("0.00");
		}
		postFee = postFee.multiply(new BigDecimal(total));
		map.put("postMoney", postFee.multiply(new BigDecimal(paramMap.get("total").toString())));

		return R.ok().put("data",map);
	}

	@Override
	public R confirmCartOrder(Map<String, Object> params) {
		String userId = params.get("userId").toString();
		MemberUserDO user = memberUserDao.get(userId);

		int level = 0;
		if(user.getLevel()==2){
			MallCompanyUserDO mallCompanyUserDO= mallCompanyUserDao.getByUserId(userId);
			if(mallCompanyUserDO==null){
				return R.error("企业信息有误");
			}else if(StringUtils.isBlank(mallCompanyUserDO.getName())){
				return R.ok(0,"企业信息不全,请补全信息再下单").put("flag",0);
			}else if(mallCompanyUserDO.getLevel()==1){
				level=1;
			}

		}
		int disabled = user.getDisabled();
		if (disabled == 1) {
			return R.error(2,"该账号已经冻结，请联系平台管理员");
		}
		List<String> cartList = (List<String>)params.get("cartList"); //商品集合
		List<Map<String,Object>> list = new ArrayList<>();
		//店铺id
		//String storeId = "";
		for (String cartMap : cartList) {
			String cartId = cartMap;  //购物车id
			MemberCartDO cart = memberCartDao.get(cartId);
			String productId = cart.getProductId();
			String goodsId = cart.getGoodsId();

			int total = cart.getNum();
			GoodsGoodsDO  goodsGoods=goodsGoodsDao.get(goodsId);
			GoodsProductDO product = goodsProductDao.get(productId);
			if (total<1){
				return R.error("购买数量不能小于1");
			}
			if (total>product.getStock()){
				return R.error("商品库存不足");
			}
			//storeId = product.getStoreId();


			int stock = product.getStock();  //库存
			if (stock < total) {
				return R.error("商品库存不足，请选择其他商品");
			}

			Map<String, Object> map = new HashMap<>();
			map.put("goodsId", goodsId);
			map.put("productId", productId);
			map.put("name", goodsGoods.getName());
			map.put("goodsImg", goodsGoods.getImgurl());
			map.put("total", total);
			map.put("price", product.getPrice());
			BigDecimal price = product.getPrice();
			map.put("allPrice", price.multiply(new BigDecimal(total)));
			MallShopUserDO mallShopUserDO = mallShopUserDao.get(goodsGoods.getShopId());
			if(mallShopUserDO!=null){
				map.put("shopName", mallShopUserDO.getName());
			}else{
				map.put("shopName", "");
			}

			map.put("costMoney", goodsGoods.getCostMoney());
			map.put("postMoney", goodsGoods.getPostFee());

			list.add(map);
		}



		return R.ok().put("data", list).put("level",level);
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public void receivingOrderJob() {
		System.out.println("11111111111111111111111111111111111111111");
		int value = orderSetDao.list(new HashMap<String, Object>()).get(0).getValue();
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS);
		Date aa = DateUtils.subDayOfDate(date, value);
		String day = format.format(aa);// 几天前的时间
		List<OrderOrderDO> orderList = orderOrderDao.receivingOrderJob(aa);
		for (OrderOrderDO order : orderList) {
			if(order.getStatus()==4){
				order.setStatus(7);
				order.setEndAt(date);
				order.setUpdateAt(date);
				orderOrderDao.update(order);

			}else if(order.getStatus()==1){
				order.setStatus(8);
				order.setUpdateAt(date);
				orderOrderDao.update(order);
				List<Map<String, Object>> byOrderId = orderDetailDao.getByOrderId(order.getId());
				if(byOrderId.size()>0){
					for (Map<String, Object> detailMap : byOrderId) {
						GoodsProductDO goodsProductDO = goodsProductDao.get(detailMap.get("productId").toString());
						goodsProductDO.setStock(goodsProductDO.getStock()+Integer.parseInt(detailMap.get("total").toString()));
						goodsProductDao.update(goodsProductDO);
					}
				}


			}

		}
	}

	/**
	 *      * 在原日期的基础上减少天数      * @param date      * @param i      * @return    
	 *  
	 */
	public static Date subDayOfDate(Date date, int i) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DATE, -i);
		Date newDate = c.getTime();
		return newDate;
	}


}
